package org.example.config;

import org.example.model.UserInfoToken;
import org.example.service.LdapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @Author: LiFuqiang
 * @Date: 2020/9/29 14:14
 * @Version 1.0
 * @description
 */
public class LdapAuthProvider implements AuthenticationProvider {


    @Autowired
    private LdapService ldapService;

    public LdapAuthProvider() {
        SpringBootBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String userName = authentication.getName();
        String password = (String) authentication.getCredentials();
        if (ldapService.authenticate(userName, password)) {

            Collection<? extends GrantedAuthority> grantedAuthorities = ldapService.listRoles(userName).stream().map(x -> new SimpleGrantedAuthority(x)).collect(Collectors.toList());
            UserInfoToken authRequest = new UserInfoToken(
                    userName, "123456", grantedAuthorities);
            authRequest.setToken("999999999");
            return authRequest;
        }

        return authentication;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
